package com.why.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.why.client.DictFeignClient;
import com.why.hosp.repository.HospitalRepository;
import com.why.hosp.service.DepartmentService;
import com.why.hosp.service.HospitalService;
import com.why.yygh.enums.DictEnum;
import com.why.yygh.model.hosp.Hospital;
import com.why.yygh.vo.hosp.HospitalQueryVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: yygh_parent
 * @description:
 * @author: @why
 * @create: 2021-06-09 08:11
 **/
@Service
public class HospitalServiceImpl implements HospitalService {
    @Autowired
    private HospitalRepository hospitalRepository;
    @Autowired
    private DictFeignClient client;

    @Autowired
    private DepartmentService departmentService;
    @Override
    public void save(Map<String, Object> switchMap) {
//        判断是否存在相同数据 存在添加 不存在更新。

        String json = JSONObject.toJSONString(switchMap);
        Hospital hospital = JSONObject.parseObject(json, Hospital.class);
//查询是否存在 getHoscode医院的唯一编号

        Hospital targetHospital = hospitalRepository.getHospitalByHoscode(hospital.getHoscode());
//        不是空，说明是更新操作
        if (Objects.nonNull(targetHospital)) {
            hospital.setStatus(targetHospital.getStatus());
            hospital.setCreateTime(targetHospital.getCreateTime());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);
//            是空 说明的插入操作
        } else {
            //0：未上线 1：已上线
            hospital.setStatus(0);
            hospital.setCreateTime(new Date());
            hospital.setUpdateTime(new Date());
            hospital.setIsDeleted(0);

        }
        hospitalRepository.save(hospital);

    }

    @Override
    public Hospital getByHoscode(String hoscode) {
        return hospitalRepository.getHospitalByHoscode(hoscode);
    }

    /**
     * 查询所有的医院信息
     *
     * @param page
     * @param limit
     * @param hospitalQueryVo
     * @return
     */
    @Override
    public Page<Hospital> selectPage(Integer page, Integer limit, HospitalQueryVo hospitalQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
//0为第一页
        Pageable pageable = PageRequest.of(page - 1, limit, sort);
        Hospital hospital = new Hospital();
        BeanUtils.copyProperties(hospitalQueryVo, hospital);
//创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

        //创建实例
        Example<Hospital> example = Example.of(hospital, matcher);
//        查询出所有的医院信息，但是没有该医院对应的等级信息
        Page<Hospital> pages = hospitalRepository.findAll(example, pageable);

        List<Hospital> content = pages.getContent();


        //            获取医院的等级
        content.forEach(this::packHospital);


        return pages;
    }

    /**
     * 封装数据  完成对医院其他属性的封装
     *
     * @param hospital
     * @return
     */
    private Hospital packHospital(Hospital hospital) {
//        远程调用接口，根据Dict_code为医院等级，和当前医院的类型获取到该医院再数据字典中的等级
//        dict_code=dict_code,value=hostType
        String hostypeString = client.getName(DictEnum.HOSTYPE.getDictCode(), hospital.getHostype());
//        根据value获取省份
        String provinceString = client.getName(hospital.getProvinceCode());
//        根据value获取城市
        String cityString = client.getName(hospital.getCityCode());
//  ·       根据vlaue获取区
        String districtString = client.getName(hospital.getDistrictCode());
//        最后将数据放到map集合，留给前端调用
//        注意，该map是
        hospital.getParam().put("hostypeString", hostypeString);
        hospital.getParam().put("fullAddress", provinceString + cityString + districtString + hospital.getAddress());
        return hospital;
    }

    @Override
    public void updateStatus(String id, Integer status) {
        if (status.intValue() == 0 || status.intValue() == 1) {
            Hospital hospital = hospitalRepository.findById(id).get();
            hospital.setStatus(status);
            hospital.setUpdateTime(new Date());
            hospitalRepository.save(hospital);
        }
    }

    /**
     * 根据id来显示
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, Object> show(String id) {
        Map<String, Object> result = new HashMap<>();
//        设置医院的各种信息 例如等级 省份等等
        Hospital hospital = this.packHospital(this.getById(id));
        result.put("hospital", hospital);
//单独处理更直观  得到预约挂号的信息
        result.put("bookingRule", hospital.getBookingRule());
//不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }

    @Override
    public String getHospName(String hoscode) {
      Hospital hospital = hospitalRepository.getHospitalByHoscode(hoscode);

        return hospital.getHosname();
    }

    private Hospital getById(String id) {

        return this.hospitalRepository.findById(id).get();

    }

    @Override
    public List<Hospital> findByHosname(String hosname) {
        return hospitalRepository.findHospitalByHosnameLike(hosname);
    }

    @Override
    public Map<String, Object> item(String hoscode) {
        Map<String, Object> result = new HashMap<>();
        //医院详情
        Hospital hospital = this.packHospital(this.getByHoscode(hoscode));
        result.put("hospital", hospital);
        //预约规则  是hospital 的一个内部属性 别整错了 不是排班
        result.put("bookingRule", hospital.getBookingRule());
        //不需要重复返回
        hospital.setBookingRule(null);
        return result;
    }



}
